<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class ClassifyController extends AdminbaseController{
    
	protected $classify_model;
	
	public function _initialize() {
		parent::_initialize();
		$this->classify_model = D("Common/Classify");
	}
	
	// 后台分类列表
	public function index(){
		$classifys=$this->classify_model->where(array('status'=>1))->order('listorder')->select();
		$this->assign("classifys",$classifys);
		$this->display();
	}
	
	// 分类添加
	public function add(){
        //        查询所有一级分类
        $classify=$this->classify_model->where('pid = 0 ')->select();
        $this->assign('classifies',$classify);
		$this->display();
	}
	
	// 分类添加提交
	public function add_post(){
        $_POST['create_time'] = date("Y-m-d H:i:s", time());
        $_POST['creator_id'] = get_current_admin_id();
        if (IS_POST) {
            if ($this->classify_model->create() !== false) {
                if ($this->classify_model->add() !== false) {

                    $this->success(L('ADD_SUCCESS'), U("Classify/index"));
                } else {
                    $this->error(L('ADD_FAILED'));
                }
            } else {
                $this->error($this->classify_model->getError());
            }

        }
	}
	
	// 分类编辑
	public function edit(){
        $_POST['update_time'] = date("Y-m-d H:i:s", time());
        $_POST['updator_id'] = get_current_admin_id();
		$id=I("get.id",0,'intval');
		$classify=$this->classify_model->where(array('id'=>$id))->find();
        //        查询所有一级分类
        $classifiess=$this->classify_model->where('pid = 0')->select();
        foreach ($classifiess as $vo){
            if($vo['id'] == $classify['pid']){
                $vo['cookselected'] = 'selected';
            }else{
                $vo['cookselected'] = '';
            }
            if($vo['id'] != $classify['id']){
                $classifies[] = $vo;
            }
        }
        $classify['classifies'] = $classifies;
		$this->assign($classify);

		$this->display();
	}
	
	// 分类编辑提交
	public function edit_post(){
		if (IS_POST) {
			if ($this->classify_model->create()!==false) {
				if ($this->classify_model->save()!==false) {
					$this->success("保存成功！", U("Classify/index"));
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->classify_model->getError());
			}
		}
	}
	
	// 分类删除
	public function delete(){
		$id = I("get.id",0,"intval");
		if ($this->classify_model->delete($id)!==false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

    //分类排序
    public function listorders() {
        $status = parent::_listorders($this->classify_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
	
}